<template>
  <div class="app-container">
    <div class="layout-container">
      <!-- 左侧：部门-岗位树 -->
      <div class="left-panel" :style="{ width: leftPanelWidth + 'px' }">
        <el-card shadow="never" style="height: calc(100vh - 120px)">
          <div slot="header">
            <span>部门岗位</span>
          </div>
          <!-- 搜索框 -->
          <el-input
            v-model="searchTreeValue"
            placeholder="请输入部门或岗位名称"
            prefix-icon="el-icon-search"
            clearable
            size="small"
            style="margin-bottom: 10px"
            @input="handleTreeSearch"
          />
          <!-- 部门-岗位树 -->
          <el-tree
            :data="treeData"
            :props="treeProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            :default-expand-all="false"
            node-key="deptId"
            ref="tree"
            highlight-current
            @node-click="handleNodeClick"
            @node-expand="handleNodeExpand"
            @node-collapse="handleNodeCollapse"
          >
            <span class="custom-tree-node" slot-scope="{ node, data }">
              <span>
                <i :class="getNodeIcon(data)" style="margin-right: 5px"></i>
                {{ node.label }}
              </span>
            </span>
          </el-tree>
        </el-card>
      </div>

      <!-- 可拖拽的分割线 -->
      <div
        class="splitter"
        @mousedown="startResize"
        :class="{ 'resizing': isResizing }"
      >
        <i class="el-icon-more" style="transform: rotate(90deg);"></i>
      </div>

      <!-- 右侧：SpreadJS表格 -->
      <div class="right-panel" :style="{ width: 'calc(100% - ' + (leftPanelWidth + 10) + 'px)' }">
        <el-card shadow="never">
      <div slot="header" class="clearfix">
            <span>{{ currentPostName || currentDeptName || '请选择岗位' }}</span>
            <div style="float: right;" v-if="currentPostCode">
          <el-button type="primary" size="small" icon="el-icon-refresh" @click="handleRefresh">刷新</el-button>
          <el-button type="success" size="small" icon="el-icon-check" @click="handleSave">保存</el-button>
          <el-button type="info" size="small" icon="el-icon-download" @click="handleExport">导出</el-button>
          <el-button type="warning" size="small" icon="el-icon-upload2" @click="handleImport">导入</el-button>
        </div>
      </div>

          <!-- 提示信息 -->
          <div v-if="!currentPostCode && !showNoPostWarning" style="text-align: center; padding: 100px 0; color: #909399">
            <i class="el-icon-info" style="font-size: 48px"></i>
            <p style="margin-top: 20px; font-size: 14px">请从左侧树中选择岗位查看数据</p>
          </div>

          <!-- 无模板提示 -->
          <div v-else-if="showNoTemplateWarning" style="text-align: center; padding: 100px 0; color: #E6A23C">
            <i class="el-icon-warning" style="font-size: 48px"></i>
            <p style="margin-top: 20px; font-size: 14px; margin-bottom: 20px">该岗位还未设置模板，请先设置模板数据</p>
            <el-button type="primary" icon="el-icon-setting" @click="goToTemplateManage">
              前往模板设置
            </el-button>
          </div>

          <!-- 无岗位提示 -->
          <div v-else-if="showNoPostWarning" style="text-align: center; padding: 100px 0; color: #F56C6C">
            <i class="el-icon-user-solid" style="font-size: 48px"></i>
            <p style="margin-top: 20px; font-size: 14px; margin-bottom: 20px">{{ currentDeptName }} 部门下还未设置岗位，请先设置岗位</p>
            <el-button type="primary" icon="el-icon-plus" @click="goToPostManage">
              前往岗位设置
            </el-button>
          </div>

          <!-- SpreadJS表格 -->
          <div v-else v-loading="loading" style="height: calc(100vh - 200px);">
        <spread-js
          ref="spreadjs"
              :key="spreadjsKey"
          :columns="columns"
          :data="tableData"
          :readonly="readonly"
          :use-designer="true"
          :header-readonly="true"
          :enforce-column-permissions="true"
          :container-id="spreadjsId"
          :enable-pagination="true"
          :page-size="100"
          @ready="handleSpreadJSReady"
          @load-more="handleLoadMore"
              @sheet-changed="handleSheetChanged"
          @save-shortcut="handleSave"
          @refresh-shortcut="handleRefresh"
        />
      </div>
        </el-card>

      <!-- 导入对话框 -->
      <el-dialog title="导入Excel" :visible.sync="importDialogVisible" width="400px" append-to-body>
        <el-upload
          class="upload-demo"
          drag
          :auto-upload="false"
          :on-change="handleFileChange"
          :file-list="fileList"
          accept=".xlsx,.xls"
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip">只能上传xlsx/xls文件</div>
        </el-upload>
        <div slot="footer" class="dialog-footer">
          <el-button @click="importDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="confirmImport">确 定</el-button>
        </div>
      </el-dialog>
      </div>
    </div>
  </div>
</template>

<script>
import SpreadJS from '@/components/SpreadJS/index.vue'
import { getDeptPostTree, getTalentData, saveTalentData, getRecruitmentStatusDict } from '@/api/talent/data'

export default {
  name: 'TalentData',
  components: {
    'spread-js': SpreadJS
  },
  data() {
    return {
      // 布局相关
      leftPanelWidth: 250, // 左侧面板宽度
      isResizing: false, // 是否正在拖拽调整
      startX: 0, // 拖拽开始的 X 坐标
      startWidth: 0, // 拖拽开始时左侧面板的宽度
      // 树相关
      searchTreeValue: '',
      treeData: [],
      treeProps: {
        children: 'children',
        label: 'deptName'
      },
      // 当前选中的岗位
      currentPostCode: '',
      currentPostName: '',
      currentPostId: '', // 当前岗位ID，用于跳转到模板设置
      currentDeptName: '', // 当前部门名称
      // 遮罩层
      loading: false,
      // 模板信息
      templateInfo: {},
      // 列配置
      columns: [],
      // 表格数据
      tableData: [],
      // 是否只读
      readonly: false,
      // 多sheet相关
      availableSheets: [],
      currentSheetName: null,
      sheetsInitialized: false, // 标记sheet是否已初始化
      // 无模板警告
      showNoTemplateWarning: false,
      // 无岗位警告
      showNoPostWarning: false,
      // 导入对话框
      importDialogVisible: false,
      // 文件列表
      fileList: [],
      // 导入文件
      importFile: null,
      // SpreadJS容器ID（唯一）
      spreadjsId: 'talent-data-spreadjs-' + Date.now(),
      // SpreadJS组件key（用于强制重新渲染）
      spreadjsKey: 1,
      // SpreadJS是否已就绪
      spreadjsReady: false,
      // 待初始化的分页数据
      pendingPaginationData: null,
      // 保存的树状态
      savedTreeState: {
        expandedKeys: [], // 展开的节点keys
        selectedKey: null, // 选中的节点key
        selectedNodeData: null // 选中的节点数据
      }
    }
  },
  created() {
    // 从 localStorage 加载用户保存的左侧面板宽度
    const savedWidth = localStorage.getItem('talent-data-left-panel-width')
    if (savedWidth) {
      this.leftPanelWidth = parseInt(savedWidth) || 300
    }
    
    // 恢复树状态
    this.restoreTreeState()
    
    this.loadTree()
  },
  activated() {
    // 页面激活时恢复树状态（用于Tab切换回来）
    console.log('=== Tab页面激活 ===')
    this.restoreTreeState()
    
    // 等待DOM更新后恢复树的展开和选中状态
    this.$nextTick(() => {
      setTimeout(() => {
        if (this.$refs.tree && this.savedTreeState.expandedKeys && this.savedTreeState.expandedKeys.length > 0) {
          console.log('Tab激活-恢复展开的节点:', this.savedTreeState.expandedKeys)
          this.savedTreeState.expandedKeys.forEach(key => {
            const node = this.$refs.tree.getNode(key)
            console.log('Tab激活-尝试展开节点:', key, '节点对象:', node)
            if (node) {
              node.expanded = true
            }
          })
        }
        
        // 恢复选中的节点
        if (this.$refs.tree && this.savedTreeState.selectedKey) {
          console.log('Tab激活-恢复选中的节点:', this.savedTreeState.selectedKey)
          this.$refs.tree.setCurrentKey(this.savedTreeState.selectedKey)
        }
        
        // 如果有保存的岗位数据，确保数据也被加载
        if (this.currentPostCode && !this.tableData.length) {
          console.log('Tab激活时恢复岗位数据:', this.currentPostCode)
    this.loadData()
        }
      }, 100) // 延迟100ms确保树完全渲染
    })
  },
  mounted() {
    // 添加全局事件监听器，用于拖拽功能
    document.addEventListener('mousemove', this.handleMouseMove)
    document.addEventListener('mouseup', this.handleMouseUp)
  },
  beforeDestroy() {
    // 移除全局事件监听器
    document.removeEventListener('mousemove', this.handleMouseMove)
    document.removeEventListener('mouseup', this.handleMouseUp)
  },
  methods: {
    /** 保存树状态到localStorage */
    saveTreeState() {
      const state = {
        expandedKeys: this.savedTreeState.expandedKeys,
        selectedKey: this.savedTreeState.selectedKey,
        selectedNodeData: this.savedTreeState.selectedNodeData,
        currentPostCode: this.currentPostCode,
        currentPostName: this.currentPostName,
        currentPostId: this.currentPostId,
        currentDeptName: this.currentDeptName,
        currentSheetName: this.currentSheetName // 保存当前sheet状态
      }
      localStorage.setItem('talent-data-tree-state', JSON.stringify(state))
    },

    /** 从localStorage恢复树状态 */
    restoreTreeState() {
      try {
        const saved = localStorage.getItem('talent-data-tree-state')
        console.log('尝试恢复树状态，localStorage数据:', saved)
        if (saved) {
          const state = JSON.parse(saved)
          this.savedTreeState.expandedKeys = state.expandedKeys || []
          this.savedTreeState.selectedKey = state.selectedKey
          this.savedTreeState.selectedNodeData = state.selectedNodeData
          
          console.log('恢复的树状态:', {
            expandedKeys: this.savedTreeState.expandedKeys,
            selectedKey: this.savedTreeState.selectedKey
          })
          
          // 恢复当前选中的岗位信息
          if (state.currentPostCode) {
            this.currentPostCode = state.currentPostCode
            this.currentPostName = state.currentPostName || ''
            this.currentPostId = state.currentPostId || ''
            this.currentDeptName = state.currentDeptName || ''
            this.currentSheetName = state.currentSheetName || null // 恢复sheet状态
            console.log('恢复的岗位信息:', state.currentPostCode, '当前sheet:', this.currentSheetName)
          }
        } else {
          console.log('没有保存的树状态')
        }
      } catch (e) {
        console.error('恢复树状态失败:', e)
      }
    },

    /** 节点展开事件 */
    handleNodeExpand(data, node) {
      const key = data.deptId
      if (!this.savedTreeState.expandedKeys.includes(key)) {
        this.savedTreeState.expandedKeys.push(key)
        console.log('节点展开，保存状态:', key, '当前展开keys:', this.savedTreeState.expandedKeys)
        this.saveTreeState()
      }
    },

    /** 节点折叠事件 */
    handleNodeCollapse(data, node) {
      const key = data.deptId
      const index = this.savedTreeState.expandedKeys.indexOf(key)
      if (index > -1) {
        this.savedTreeState.expandedKeys.splice(index, 1)
        console.log('节点折叠，保存状态:', key, '当前展开keys:', this.savedTreeState.expandedKeys)
        this.saveTreeState()
      }
    },

    /** 开始拖拽调整 */
    startResize(event) {
      this.isResizing = true
      this.startX = event.clientX
      this.startWidth = this.leftPanelWidth
      event.preventDefault()
    },

    /** 拖拽过程中 */
    handleMouseMove(event) {
      if (!this.isResizing) return

      const deltaX = event.clientX - this.startX
      const newWidth = this.startWidth + deltaX

      // 限制最小和最大宽度
      const minWidth = 200
      const maxWidth = window.innerWidth * 0.6 // 最大不超过屏幕宽度的60%

      if (newWidth >= minWidth && newWidth <= maxWidth) {
        this.leftPanelWidth = newWidth
      }
    },

    /** 结束拖拽 */
    handleMouseUp() {
      if (this.isResizing) {
        this.isResizing = false
        // 保存用户设置到 localStorage
        localStorage.setItem('talent-data-left-panel-width', this.leftPanelWidth.toString())
      }
    },

    /** 加载部门-岗位树 */
    loadTree() {
      getDeptPostTree(this.searchTreeValue).then(response => {
        this.treeData = response.data.tree
        
        // 树数据加载完成后，稍等一下确保树完全渲染，然后手动展开保存的节点
        this.$nextTick(() => {
          setTimeout(() => {
            if (this.$refs.tree && this.savedTreeState.expandedKeys && this.savedTreeState.expandedKeys.length > 0) {
              console.log('恢复展开的节点:', this.savedTreeState.expandedKeys)
              this.savedTreeState.expandedKeys.forEach(key => {
                const node = this.$refs.tree.getNode(key)
                console.log('尝试展开节点:', key, '节点对象:', node)
                if (node) {
                  node.expanded = true
                }
              })
            }
            
            // 恢复选中的节点
            if (this.$refs.tree && this.savedTreeState.selectedKey) {
              console.log('恢复选中的节点:', this.savedTreeState.selectedKey)
              this.$refs.tree.setCurrentKey(this.savedTreeState.selectedKey)
            }
            
            // 如果有保存的岗位数据，在树加载完成后自动加载对应的数据
            if (this.currentPostCode && !this.tableData.length) {
              console.log('自动恢复岗位数据:', this.currentPostCode)
              this.loadData()
            }
          }, 100) // 延迟100ms确保树完全渲染
        })
      })
    },

    /** 树搜索 */
    handleTreeSearch() {
      // 触发树组件的过滤功能
      this.$refs.tree.filter(this.searchTreeValue)
    },

    /** 过滤树节点 */
    filterNode(value, data) {
      if (!value) return true
      // 模糊搜索：支持部门名称和岗位名称
      return data.deptName.toLowerCase().includes(value.toLowerCase())
    },

    /** 获取节点图标 */
    getNodeIcon(data) {
      // 如果status字段以POST:开头，表示这是岗位节点
      if (data.status && data.status.startsWith('POST:')) {
        return 'el-icon-user'
      }
      return 'el-icon-office-building'
    },

    /** 树节点点击 */
    handleNodeClick(data) {
      // 重置所有警告状态
      this.showNoTemplateWarning = false
      this.showNoPostWarning = false
      
      // 保存选中的节点状态
      this.savedTreeState.selectedKey = data.deptId
      this.savedTreeState.selectedNodeData = data
      
      // 判断是否是岗位节点
      if (data.status && data.status.startsWith('POST:')) {
        // 提取postCode和postId
        const postCode = data.status.substring(5) // 去掉"POST:"前缀
        const postId = data.deptId // 岗位节点的deptId实际存储的是postId
        console.log('点击岗位节点:', data.deptName, '完整status:', data.status, '提取的postCode:', postCode, '岗位ID:', postId)
        this.currentPostCode = postCode
        this.currentPostId = postId
        this.currentPostName = data.deptName + '人才库'
        this.currentDeptName = ''
        
        // 切换岗位时，通过更新key强制重新创建SpreadJS组件，实现完全重置
        this.spreadjsKey += 1
        this.spreadjsId = 'talent-data-spreadjs-' + Date.now()
        this.spreadjsReady = false
        this.pendingPaginationData = null
        
        // 重置sheet状态
        this.sheetsInitialized = false
        this.availableSheets = []
        this.currentSheetName = null
        
        // 保存状态
        this.saveTreeState()
        
        this.loadData()
      } else {
        // 部门节点
        console.log('点击部门节点:', data.deptName)
        this.currentDeptName = data.deptName
        this.currentPostCode = ''
        this.currentPostName = ''
        this.currentPostId = ''
        
        // 保存状态
        this.saveTreeState()
        
        // 检查部门下是否有岗位
        const hasPost = this.checkDeptHasPost(data)
        if (!hasPost) {
          this.showNoPostWarning = true
        }
      }
    },

    /** 检查部门下是否有岗位 */
    checkDeptHasPost(deptNode) {
      // 如果部门有子节点
      if (deptNode.children && deptNode.children.length > 0) {
        // 遍历子节点，查看是否有岗位节点或子部门有岗位
        for (let child of deptNode.children) {
          // 如果是岗位节点（status以POST:开头）
          if (child.status && child.status.startsWith('POST:')) {
            return true
          }
          // 如果是部门节点，递归检查
          if (!child.status || !child.status.startsWith('POST:')) {
            if (this.checkDeptHasPost(child)) {
              return true
            }
          }
        }
      }
      return false
    },

    /** 加载数据（支持分页和sheet切换） */
    loadData(page = 1, pageSize = 100, sheetName = null) {
      if (!this.currentPostCode) return

      // 如果是第一次加载且没有初始化sheets，需要先检查是否需要初始化
      if (!this.sheetsInitialized && !sheetName) {
        this.initializeSheets(page, pageSize)
        return
      }

      // 正常加载数据
      this.loadSheetData(page, pageSize, sheetName)
    },

    /** 初始化sheet标签页 */
    initializeSheets(page = 1, pageSize = 100) {
      console.log('[TalentData] 开始初始化sheets')
      this.loading = true

      // 先获取模板字段信息，检查是否有招聘状态字段
      getTalentData(this.currentPostCode, 1, 1).then(response => {
        const result = response.data
        
        // 转换字段配置
        this.columns = result.fields.map(field => {
          const columnWidth = field.columnWidth || 120
          console.log(`[TalentData] 字段 "${field.fieldLabel}" 后端宽度: ${field.columnWidth}, 最终宽度: ${columnWidth}`)
          return {
          fieldName: field.fieldName,
          fieldLabel: field.fieldLabel,
          fieldType: field.fieldType,
            cellTypeConfig: field.cellTypeConfig,
          sortOrder: field.sortOrder,
          isRequired: field.isRequired,
          permissionType: field.permissionType,
            readonly: field.permissionType === '0',
            width: columnWidth
          }
        })

        this.templateInfo = result.template
        this.readonly = !result.fields.some(f => f.permissionType === '1')

        // 检查是否有招聘状态字段
        const hasRecruitmentStatus = result.fields.some(field => field.fieldLabel === '招聘状态')
        
        if (hasRecruitmentStatus) {
          console.log('[TalentData] 检测到招聘状态字段，查询字典初始化sheets')
          
          // 查询招聘状态字典
          getRecruitmentStatusDict().then(dictResponse => {
            const dictData = dictResponse.data
            
            if (dictData && dictData.length > 0) {
              // 根据字典初始化sheet数据
              this.availableSheets = dictData.map(item => ({
                name: item.dictLabel,
                value: item.dictValue
              }))
              
              // 设置默认当前sheet为第一个
              this.currentSheetName = this.availableSheets[0].name
              this.sheetsInitialized = true
              
              console.log('[TalentData] ✓ 获取到', this.availableSheets.length, '个sheets:', this.availableSheets.map(s => s.name))
              
              // 保存多sheet初始化数据，等SpreadJS ready后处理
              this.pendingPaginationData = {
                multiSheet: true,
                availableSheets: this.availableSheets,
                loadData: { page, pageSize, sheetName: this.currentSheetName }
              }
              
              // 如果SpreadJS已就绪，立即处理
              if (this.spreadjsReady && this.$refs.spreadjs) {
                console.log('[TalentData] SpreadJS已就绪，立即创建多sheet')
                this.$refs.spreadjs.initMultiSheet(this.availableSheets)
                // 注意：不在这里手动加载数据，因为initMultiSheet会自动触发sheet-changed事件
                this.pendingPaginationData = null
              } else {
                console.log('[TalentData] SpreadJS未就绪，等待ready事件')
              }
            } else {
              console.log('[TalentData] 字典数据为空，使用单sheet模式')
              this.initializeSingleSheet(page, pageSize)
            }
          }).catch(error => {
            console.error('[TalentData] 查询字典失败:', error)
            this.initializeSingleSheet(page, pageSize)
          })
        } else {
          console.log('[TalentData] 未检测到招聘状态字段，使用单sheet模式')
          this.initializeSingleSheet(page, pageSize)
        }
      }).catch(error => {
        console.warn('岗位模板数据加载失败:', error.msg || error)
        this.showNoTemplateWarning = true
        this.columns = []
        this.tableData = []
        this.loading = false
      })
    },

    /** 初始化单sheet模式 */
    initializeSingleSheet(page, pageSize) {
      this.availableSheets = []
      this.currentSheetName = null
      this.sheetsInitialized = true
      
      // 加载数据
      this.loadSheetData(page, pageSize, null)
    },

    /** 加载指定sheet的数据 */
    loadSheetData(page = 1, pageSize = 100, sheetName = null) {
      console.log('[TalentData] ========== 开始加载sheet数据 ==========')
      console.log('[TalentData] 参数 - page:', page, 'pageSize:', pageSize, 'sheetName:', sheetName)
      console.log('[TalentData] 岗位代码:', this.currentPostCode)
      console.log('[TalentData] availableSheets数量:', this.availableSheets.length)
      
      if (!this.currentPostCode) {
        console.error('[TalentData] 岗位代码为空，无法加载数据')
        return
      }
      
      this.loading = true
      
      getTalentData(this.currentPostCode, page, pageSize, sheetName).then(response => {
        console.log('[TalentData] API响应成功:', response)
        const result = response.data
        
        console.log('[TalentData] 返回数据结构:')
        console.log('  - result.data数量:', result.data ? result.data.length : 'null')
        console.log('  - result.total:', result.total)
        console.log('  - result.fields数量:', result.fields ? result.fields.length : 'null')
        console.log('  - 多sheet模式:', this.availableSheets.length > 1)

      // 更新当前sheet名称
      if (sheetName) {
        this.currentSheetName = sheetName
        console.log('[TalentData] 更新当前sheet名称为:', this.currentSheetName)
        // 保存sheet状态
        this.saveTreeState()
      }

        // 统一数据处理
          this.tableData = result.data || []
        console.log('[TalentData] 处理后的tableData数量:', this.tableData.length)

        // 如果SpreadJS已就绪，立即更新当前sheet数据
        if (this.spreadjsReady && this.$refs.spreadjs) {
          console.log('[TalentData] SpreadJS已就绪，开始更新数据')
          
          if (this.availableSheets.length > 1) {
            // 多sheet模式：更新当前sheet的数据，传递total支持分页
            console.log('[TalentData] 使用多sheet模式更新数据，total:', result.total)
            this.$refs.spreadjs.updateCurrentSheetData(this.tableData, result.total || 0)
          } else {
            // 单sheet模式：使用原有的分页初始化
            console.log('[TalentData] 使用单sheet模式初始化数据，total:', result.total)
            this.$refs.spreadjs.initPaginationData(this.tableData, result.total || 0)
          }
          this.loading = false
          console.log('[TalentData] 数据更新完成，loading设为false')
        } else {
          console.log('[TalentData] SpreadJS未就绪，保存待初始化数据')
          // 保存待初始化的数据，等SpreadJS ready后处理
          this.pendingPaginationData = {
            data: this.tableData,
            total: result.total || 0
          }
        }
        
        console.log('[TalentData] ========== sheet数据加载完成 ==========')
      }).catch(error => {
        console.error('[TalentData] sheet数据加载失败:', error)
        console.error('[TalentData] 错误详情:', error.msg || error.message || error)
        this.loading = false
      })
    },
    
    /** SpreadJS组件就绪事件 */
    handleSpreadJSReady() {
      this.spreadjsReady = true
      
      // 如果有待初始化的数据，现在初始化
      if (this.pendingPaginationData && this.$refs.spreadjs) {
        if (this.pendingPaginationData.multiSheet) {
          // 多sheet模式：先创建sheets（会自动触发第一个sheet的数据加载）
          console.log('[TalentData] 在ready事件中创建多sheet')
          this.$refs.spreadjs.initMultiSheet(this.pendingPaginationData.availableSheets)
          // 注意：不在这里手动加载数据，因为initMultiSheet会自动触发sheet-changed事件
        } else {
          // 单sheet模式
        this.$refs.spreadjs.initPaginationData(this.pendingPaginationData.data, this.pendingPaginationData.total)
          this.loading = false
        }
        this.pendingPaginationData = null
      }
    },

    /** 处理sheet切换事件 */
    handleSheetChanged(sheetName) {
      console.log('[TalentData] ==================== 处理Sheet切换 ====================')
      console.log('[TalentData] 收到sheet切换事件:', sheetName)
      console.log('[TalentData] 当前岗位代码:', this.currentPostCode)
      console.log('[TalentData] SpreadJS就绪状态:', this.spreadjsReady)
      console.log('[TalentData] 可用sheets:', this.availableSheets)
      
      if (!this.currentPostCode) {
        console.error('[TalentData] 岗位代码为空，无法加载数据')
        return
      }
      
      if (!this.spreadjsReady) {
        console.warn('[TalentData] SpreadJS未就绪，延迟处理')
        return
      }
      
      // 每次切换都重新加载数据（即使是同一个sheet，用户主动切换也应该刷新）
      console.log('[TalentData] 准备加载sheet数据，从', this.currentSheetName, '切换到', sheetName)
      
      // 重新加载指定sheet的数据
      console.log('[TalentData] 开始加载sheet数据:', sheetName)
      this.loadSheetData(1, 100, sheetName)
      console.log('[TalentData] ==================== Sheet切换处理完成 ====================')
    },

    
    /** 加载更多数据 */
    handleLoadMore(params) {
      const { page, pageSize, callback } = params
      getTalentData(this.currentPostCode, page, pageSize).then(response => {
        const result = response.data
        // 调用回调函数，追加数据
        callback(result.data || [], result.total || 0)
      }).catch(() => {
        callback([], 0)
      })
    },

    /** 刷新 */
    handleRefresh() {
      // 保存当前sheet状态
      const currentSheetBeforeRefresh = this.currentSheetName
      console.log('[TalentData] 刷新前当前sheet:', currentSheetBeforeRefresh)
      
      // 根据是否为多sheet模式决定刷新策略
      if (this.availableSheets.length > 1 && currentSheetBeforeRefresh) {
        // 多sheet模式：只刷新当前sheet的数据，保持sheet状态
        console.log('[TalentData] 多sheet模式刷新，只刷新当前sheet:', currentSheetBeforeRefresh)
        this.loadSheetData(1, 100, currentSheetBeforeRefresh)
      } else {
        // 单sheet模式：使用原有的完整刷新逻辑
        console.log('[TalentData] 单sheet模式刷新，完整刷新')
      this.loadData()
      }
    },

    /** 保存 */
    handleSave() {
      if (this.readonly) {
        this.$modal.msgError('您没有修改权限')
        return
      }

      // 从SpreadJS获取数据
      const data = this.$refs.spreadjs.getData()
      
      // 保存当前sheet状态
      const currentSheetBeforeSave = this.currentSheetName
      console.log('[TalentData] 保存前当前sheet:', currentSheetBeforeSave)
      
      this.loading = true
      saveTalentData(this.currentPostCode, data).then(response => {
        // 显示保存成功消息，包含快捷键提示
        this.$modal.msgSuccess('保存成功！快捷键提示：Ctrl+S 保存，F5 刷新')
        
        // 根据是否为多sheet模式决定刷新策略
        if (this.availableSheets.length > 1 && currentSheetBeforeSave) {
          // 多sheet模式：只刷新当前sheet的数据，保持sheet状态
          console.log('[TalentData] 多sheet模式保存成功，刷新当前sheet:', currentSheetBeforeSave)
          this.currentSheetName = currentSheetBeforeSave // 确保sheet状态正确
          this.saveTreeState() // 保存状态
          this.loadSheetData(1, 100, currentSheetBeforeSave)
        } else {
          // 单sheet模式：使用原有的刷新逻辑
          console.log('[TalentData] 单sheet模式保存成功，完整刷新')
        this.loadData()
        }
      }).catch(() => {
        this.loading = false
      })
    },

    /** 导出 */
    handleExport() {
      const fileName = `${this.currentPostName}_${new Date().getTime()}.xlsx`
      this.$refs.spreadjs.exportExcel(fileName)
    },

    /** 导入 */
    handleImport() {
      this.fileList = []
      this.importFile = null
      this.importDialogVisible = true
    },

    /** 文件变化 */
    handleFileChange(file) {
      this.importFile = file.raw
    },

    /** 确认导入 */
    confirmImport() {
      if (!this.importFile) {
        this.$modal.msgError('请选择文件')
        return
      }

      this.$refs.spreadjs.importExcel(this.importFile)
      this.importDialogVisible = false
    },

    /** 导入成功 */
    handleImportSuccess() {
      this.$modal.msgSuccess('导入成功')
    },

    /** 导入失败 */
    handleImportError(error) {
      this.$modal.msgError('导入失败：' + error)
    },

    /** 跳转到模板管理 */
    goToTemplateManage() {
      // 跳转到人才库模板管理页面
      this.$router.push('/talent/template')
    },

    /** 跳转到岗位管理 */
    goToPostManage() {
      // 跳转到系统岗位管理页面
      this.$router.push('/system/post')
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.layout-container {
  display: flex;
  height: calc(100vh - 120px);
  position: relative;
}

.left-panel {
  flex-shrink: 0;
  min-width: 200px;
  max-width: 60vw;
}

.right-panel {
  flex: 1;
  margin-left: 10px;
  overflow: hidden;
}

.splitter {
  width: 6px;
  background: #f0f2f5;
  cursor: col-resize;
  display: flex;
  align-items: center;
  justify-content: center;
  border-left: 1px solid #e8eaec;
  border-right: 1px solid #e8eaec;
  user-select: none;
  transition: background-color 0.2s;
}

.splitter:hover {
  background: #e6f7ff;
}

.splitter.resizing {
  background: #1890ff;
}

.splitter i {
  color: #999;
  font-size: 12px;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

/deep/ .el-tree-node__content {
  height: 32px;
}
</style>

